package com.sping.gobang.controller;

import com.sping.gobang.common.constant.Constants;
import com.sping.gobang.exception.UserException;
import com.sping.gobang.pojo.datapbject.User;
import com.sping.gobang.pojo.request.UserLoginRequest;
import com.sping.gobang.pojo.request.UserRegisterRequest;
//import com.sping.gobang.pojo.response.UserLoginResponse;
import com.sping.gobang.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Resource(name = "userServiceImpl")
    private UserService userService;

    @RequestMapping("/login")
    public boolean login(@RequestParam @NotBlank(message = "用户名不能为空") String username, @RequestParam @NotBlank(message = "密码不能为空") String password, HttpServletRequest req){
        log.info("进行登陆,username"+username);
        User user = userService.login(username, password);
        if(user==null){
            return false;
        }
        //如果不存在会话，则创建新会话
        HttpSession httpSession=req.getSession(true);
        httpSession.setAttribute(Constants.SESSION_USER_KEY,user);
        return true;


    }
    @RequestMapping("/register")
    public String register(@Validated @RequestBody UserRegisterRequest userRegisterRequest){
        log.info("进行注册,userRegisterRequest:{}",userRegisterRequest);
        boolean result=userService.register(userRegisterRequest);
        if(result==true){
            return "注册成功";
        }else{
            return "注册失败";
        }
    }
    @RequestMapping("/getcurrentuser")
//    返回当前登陆用户的信息
    public User getcurrentuser(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(Constants.SESSION_USER_KEY);
        String currentUsername= user.getUsername();
        if(currentUsername==null){
            throw new UserException("用户未登陆");
        }
        User user1=userService.getcurrentuser(currentUsername);
        return user1;
    }


}
